package com.caineng.zhaobiao.zbapi.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.http.HttpUtil;
import com.caineng.zhaobiao.zbapi.controller.paramVo.CaiZhaobiaoVo;
import com.caineng.zhaobiao.zbapi.dao.CaiAddressDao;
import com.caineng.zhaobiao.zbapi.dao.CaiHotWordDao;
import com.caineng.zhaobiao.zbapi.domain.*;
import com.caineng.zhaobiao.zbapi.service.CaiZhaobiaoDetailService;
import com.caineng.zhaobiao.zbapi.service.CaiZhaobiaoService;
import com.caineng.zhaobiao.zbapi.service.vo.ZhaobiaoVo;
import com.caineng.zhaobiao.zbapi.utils.AjaxResult;
import com.caineng.zhaobiao.zbapi.utils.multipleDb.MongodbConfiguration;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页查询服务
 * @author liandyao
 * @date 2022/7/18 15:46
 */
@Slf4j
@Api(tags = "首页各种公用接口查询")
@RestController
@RequestMapping("/zbapi/index")
public class IndexController {

    @Autowired
    private CaiAddressDao addressDao ;

    @Autowired
    private  CaiHotWordDao hotWordDao ;

    @Autowired
    private CaiZhaobiaoService zhaobiaoService ;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Autowired
    CaiZhaobiaoDetailService detailService ;

    @Autowired
    @Qualifier(MongodbConfiguration.MONGO_TEMPLATE_SECONDARY)
    MongoTemplate mongoTemplateSecondary ;



    @GetMapping("/findZbAll")
    @ApiOperation(value = "查询所有的招标信息")
    public AjaxResult findZbAll(CaiZhaobiaoVo zb){
        Pageable page = PageRequest.of(zb.getCurPage(), zb.getPageSize(),Sort.Direction.DESC,"publishTime");
        //第二页时需要判断是否登录
        if(zb.getCurPage()>1 && !StpUtil.isLogin()){
            return AjaxResult.noLogin("请登录");
        }
        //自己封装分页对象
        List<ZhaobiaoVo> list = zhaobiaoService.findAll(zb,page);
        Page records = new PageImpl(list,page,1000);
        return AjaxResult.success("成功",records);

    }

    @GetMapping("/findAllAddress")
    @ApiOperation(value = "查询所有的地区信息")
    public AjaxResult findAllAddress(){
        List<CaiAddress> list = addressDao.findAll();
        return AjaxResult.success("成功",list);

    }


    @GetMapping("/hotWord")
    @ApiOperation(value = "查询首页热词搜索")
    public AjaxResult hotWord(){

        List<CaiHotWord> list = hotWordDao.findAll(Sort.by("sort"));

        List<CaiHotWord> listZb = new ArrayList<CaiHotWord>();
        List<CaiHotWord> listCompany = new ArrayList<CaiHotWord>();

        for(CaiHotWord hotWord : list){
            if(hotWord.getId()<100){
                listZb.add(hotWord);
            }else if(hotWord.getId()>=100){
                listCompany.add(hotWord);
            }
        }
        Map objMap = new HashMap();
        objMap.put("zhaobiao",listZb);
        objMap.put("company",listCompany);
        return AjaxResult.success("成功",objMap);
    }

    /**
     * 小程序必须配置https的downloadFile合法域名,所以部分网站的http不满足小程序打开pdf文件
     * 所以只能使用此方法先下载到本地,然后再把本地的地址发给前端
     * @param url
     * @return
     */
    @GetMapping("/openPdfFile")
    @ApiOperation(value = "查看pdf文件-仅供小程序使用")
    public void openPdfFile(String url, HttpServletResponse response) throws IOException {
        Assert.notNull(url,"下载地址不能为空");
        log.info(url);
        OutputStream fos = response.getOutputStream();
        //下载到本地之后,再发送到前台
        HttpUtil.download(url,fos,true);

    }

    @PostMapping("/bigEventGray")
    @ApiOperation(value = "大事件灰色，如果返回1，表示出现了大事件，要加上灰色")
    public AjaxResult big_event_gray(){
        CaiSystemConfig config = mongoTemplate.findOne(Query.query(Criteria.where("name").is("big_event_gray")), CaiSystemConfig.class);

        if(config!=null && NumberUtil.parseInt(config.getValue())==1){
            return AjaxResult.success("灰色",1);
        }
        return AjaxResult.success("正常",0);
    }


    @GetMapping("/findDetail")
    @ApiOperation(value = " 0020 根据id查询招标信息-新的方法,使用自己的id作为主键")
    public AjaxResult findDetail(String id){

        CaiZhaobiao zhaobiao =zhaobiaoService.findByMyId(id);
        if(zhaobiao==null){
            return AjaxResult.error("您查看的招标找不到了");
        }

        /*boolean found = detailService.isMaxCount();
        if(!found){
            return AjaxResult.maxLimitByDay("今日查看已达到上限!");
        }*/

        //加入详情信息,一般不需要查详情,因为占用网络流量太多
        CaiZhaobiaoDetail detail = detailService.findByBusId(zhaobiao.getId());
        if(detail!=null){
            zhaobiao.setNoticeContent(detail.getContent());
        }
        return AjaxResult.success("ok",zhaobiao);
    }


    @GetMapping("/findZbProperty")
    @ApiOperation(value = "0030 根据id查询解析的招标属性")
    public AjaxResult findZbProperty(String id){

        Map map = zhaobiaoService.findZbProperty(id);
        return AjaxResult.success("ok",map);
    }


    @GetMapping("/findOnlyCompanyName")
    @ApiOperation(value = "0040 精确查询企业名称,不查询曾用名,不排序 ")
    public AjaxResult findOnlyCompanyName(String name){
        long start = System.currentTimeMillis();

        Pageable page = PageRequest.of(0, 10);
        Query query = new Query();
        query.addCriteria(Criteria.where("companyName").is(name));
        //List<CaiCompany> list = companyService.findAll(zb,page);
        //查询指定的字段
        query.with(page).fields().include("companyCid").include("companyName").include("companyHistoryNames");
        List<Map> list = mongoTemplate.find(query, Map.class,"cai_quali_company");

        //如果查询不到,查询大库
        if(list.isEmpty()){
            list=mongoTemplateSecondary.find(query, Map.class,"cai_company");
        }

        Page records = new PageImpl(list,page,1000);
        long end = System.currentTimeMillis();
        log.info("---经过的时间是--->"+(start-end)/1000);
        return AjaxResult.success("成功",records);

    }

}
